<template>
  <div class="assessment-list-container">
    <div class="page-header">
      <h2>考察信息管理</h2>
      <p>管理用户的考察评议记录</p>
    </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-blue">
              <el-icon><Aim /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.totalCount }}</div>
              <div class="stat-label">考察记录总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-green">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.userCount }}</div>
              <div class="stat-label">考察对象人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-orange">
              <el-icon><StarFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.avgScore }}分</div>
              <div class="stat-label">平均评分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-purple">
              <el-icon><TopRight /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.passRate }}%</div>
              <div class="stat-label">通过率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="考察对象">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入姓名"
              clearable
              @clear="handleInputClear('name')"
              @input="debounceSearch"
            />
          </el-form-item>
          <el-form-item label="考察类型">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择考察类型"
              clearable
              @change="handleTypeChange"
            >
              <el-option label="政治素质" :value="1" />
              <el-option label="群众评议" :value="4" />
              <el-option label="组织评议" :value="5" />
              <el-option label="综合考察" :value="6" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchAssessments">
              <el-icon><Search /></el-icon> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
            <el-button type="success" @click="handleAdd">
              <el-icon><Plus /></el-icon> 新增考察记录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 考察记录列表表格 -->
    <el-card class="table-card" shadow="hover" v-loading="loading">
      <el-table :data="assessmentList" border style="width: 100%" row-key="id">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="userName" label="考察对象" min-width="100" />
        <el-table-column prop="status" label="考察类型" min-width="120">
          <template #default="scope">
            {{ getStatusText(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="recordDate" label="记录日期" min-width="120">
           <template #default="scope">
            {{ formatDate(scope.row.recordDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="checker" label="考察人" min-width="100" />
        <el-table-column prop="inspectionScore" label="评分" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getScoreTagType(scope.row.inspectionScore)">{{ scope.row.inspectionScore }}分</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="conclusion" label="结论" min-width="100">
          <template #default="scope">
            <el-tag :type="getConclusionTagType(scope.row.conclusion)">{{ getConclusionText(scope.row.conclusion) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" plain @click="handleView(scope.row)">
                <el-icon><View /></el-icon> 查看
              </el-button>
              <el-button size="small" type="warning" plain @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button size="small" type="danger" plain @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看考察详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="考察详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border v-if="currentAssessment.id">
        <el-descriptions-item label="考察对象">{{ currentAssessment.userName }}</el-descriptions-item>
        <el-descriptions-item label="考察类型">{{ getStatusText(currentAssessment.status) }}</el-descriptions-item>
        <el-descriptions-item label="记录日期">{{ formatDate(currentAssessment.recordDate) }}</el-descriptions-item>
        <el-descriptions-item label="考察人">{{ currentAssessment.checker }}</el-descriptions-item>
        <el-descriptions-item label="评分">
          <el-tag :type="getScoreTagType(currentAssessment.inspectionScore)">{{ currentAssessment.inspectionScore }}分</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="结论">
          <el-tag :type="getConclusionTagType(currentAssessment.conclusion)">{{ getConclusionText(currentAssessment.conclusion) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="考察内容" :span="2">
          <div class="assessment-content">
            {{ currentAssessment.inspectionContent || '暂无内容' }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="问题建议" :span="2">
          <div class="assessment-suggestions">
            {{ currentAssessment.advice || '暂无建议' }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/编辑考察记录对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑考察记录' : '新增考察记录'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="assessmentForm" :rules="assessmentFormRules" ref="assessmentFormRef" label-width="100px">
        <el-form-item label="考察对象" prop="userId">
          <template v-if="isEdit">
            <el-input v-model="assessmentForm.userName" placeholder="请输入姓名" disabled />
          </template>
          <template v-else>
            <el-select
              v-model="assessmentForm.userId"
              filterable
              placeholder="请选择或搜索考察对象"
              @change="handleUserChange"
              style="width: 100%"
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.name || user.nickname || user.username"
                :value="user.id"
              />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="考察类型" prop="status">
          <el-select v-model="assessmentForm.status" placeholder="请选择考察类型" style="width: 100%">
            <el-option label="政治素质" :value="1" />
            <el-option label="群众评议" :value="4" />
            <el-option label="组织评议" :value="5" />
            <el-option label="综合考察" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker
            v-model="assessmentForm.recordDate"
            type="datetime"
            placeholder="请选择记录日期"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="考察人" prop="checker">
          <el-input v-model="assessmentForm.checker" placeholder="请输入考察人姓名" />
        </el-form-item>
        <el-form-item label="评分" prop="inspectionScore">
          <el-slider v-model="assessmentForm.inspectionScore" :step="1" :min="0" :max="100" style="width: 100%"/>
        </el-form-item>
        <el-form-item label="结论" prop="conclusion">
          <el-radio-group v-model="assessmentForm.conclusion">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">有条件通过</el-radio>
            <el-radio :label="3">不通过</el-radio>
            <el-radio :label="4">暂缓通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="考察内容" prop="inspectionContent">
          <el-input
            v-model="assessmentForm.inspectionContent"
            type="textarea"
            :rows="5"
            placeholder="请输入考察内容"
          />
        </el-form-item>
        <el-form-item label="问题建议" prop="advice">
          <el-input
            v-model="assessmentForm.advice"
            type="textarea"
            :rows="3"
            placeholder="请输入问题和改进建议"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssessment" :loading="submitting">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search, Refresh, View, Edit, Delete, Plus, Aim,
  User, StarFilled, TopRight
} from '@element-plus/icons-vue';
import {
  getAssessmentList,
  getAssessmentById,
  addAssessment,
  updateAssessment,
  deleteAssessment
} from '@/api/assessment';
import { getUserList } from '@/api/user';

// --- 状态与结论映射 ---
const STATUS_MAP = {
  1: '政治素质',
  2: '群众评议',
  3: '组织评议',
  4: '综合考察',
};

const CONCLUSION_MAP = {
  1: '通过',
  2: '有条件通过',
  3: '不通过',
  4: '暂缓通过',
};

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const assessmentList = ref([]);

// 统计数据
const statsData = reactive({
  totalCount: 0,
  userCount: 0,
  avgScore: 0,
  passRate: 0
});

// 搜索表单
const searchForm = reactive({
  name: '', // 考察对象姓名，后端可能通过此字段关联查询 userId
  status: null // 考察类型 (Integer)
});

// 详情对话框
const viewDialogVisible = ref(false);
const currentAssessment = ref({});

// 编辑对话框
const editDialogVisible = ref(false);
const isEdit = ref(false);
const assessmentFormRef = ref(null);
const initialAssessmentForm = () => ({
  id: null,
  userId: null,
  userName: '', // 用于编辑时显示，不直接提交
  status: null, // Integer
  recordDate: '', // YYYY-MM-DD HH:mm:ss
  checker: '',
  inspectionScore: 80, // Integer
  conclusion: 1, // Integer, 默认为通过
  inspectionContent: '',
  advice: ''
});
const assessmentForm = reactive(initialAssessmentForm());
const submitting = ref(false);

// 表单校验规则
const assessmentFormRules = {
  userId: [{ required: true, message: '请选择考察对象', trigger: 'change' }],
  status: [{ required: true, message: '请选择考察类型', trigger: 'change' }],
  recordDate: [{ required: true, message: '请选择记录日期', trigger: 'change' }],
  checker: [{ required: true, message: '请输入考察人姓名', trigger: 'blur' }],
  inspectionScore: [{ required: true, message: '请输入评分', trigger: 'blur' }], // el-slider自带校验，此处可简化
  conclusion: [{ required: true, message: '请选择结论', trigger: 'change' }],
  inspectionContent: [{ required: true, message: '请输入考察内容', trigger: 'blur' }]
};

// 用户列表
const userList = ref([]);

const fetchUserList = async () => {
  try {
    const response = await getUserList({ pageSize: 1000, pageNum: 1 }); // 获取所有用户
    if (response.data.code === 200) {
      userList.value = response.data.data.users || [];
    } else {
      ElMessage.error('获取用户列表失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败，请检查网络或联系管理员');
  }
};

onMounted(() => {
  fetchUserList();
  fetchAssessments();
});

const formatDate = (dateTimeStr, includeTime = false) => {
  if (!dateTimeStr) return '-';
  // 后端返回的是 LocalDateTime 字符串，通常是 "YYYY-MM-DDTHH:mm:ss" 或 "YYYY-MM-DD HH:mm:ss"
  if (includeTime) {
    return dateTimeStr.replace('T', ' ').substring(0, 19); // YYYY-MM-DD HH:mm:ss
  }
  return dateTimeStr.substring(0, 10); // YYYY-MM-DD
};

const fetchAssessments = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      // 后端期望的是 searchForm.name (考察对象姓名) 还是 userId? 假设是name，如果需要userId，则需要转换
      // 假设searchForm.name可以直接用于后端查询用户名
      userName: searchForm.name || undefined, // 使用 userName 字段给后端传参
      status: searchForm.status === '' ? undefined : searchForm.status,
    };
    // 清理 undefined 参数
    Object.keys(params).forEach(key => params[key] === undefined && delete params[key]);

    const response = await getAssessmentList(params); // API已修改为只接收一个对象
    // 假设后端返回数据结构为 { code: 200, msg: '...', data: { list: [], total: 0 } }
    // 或 { code: 200, data: { records: [], total: 0 } } 根据实际情况调整
    console.log(response.data.data.page.records);
    if (response.data.code === 200 && response.data.data) {
      // 确保后端返回了类似 InspectionLog 的对象列表，其中包含 userId, userName, status 等
      const rawAssessmentList = response.data.data.list || response.data.data.page.records || [];
      
      // 根据 userId 映射 userName
      assessmentList.value = rawAssessmentList.map(assessment => {
        const user = userList.value.find(u => u.id === assessment.userId);
        return {
          ...assessment,
          userName: user ? (user.name || user.nickname || user.username) : (assessment.userName || '未知用户')
        };
      });
      
      total.value = response.data.data.total || response.data.data.page?.total || 0; // 适配不同的分页结构
      
      updateStatsData();
    } else {
      ElMessage.error(response.data.msg || '获取考察记录列表失败');
    }
  } catch (error) {
    console.error('获取考察记录列表失败:', error);
    ElMessage.error('获取考察记录列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const updateStatsData = () => {
  statsData.totalCount = total.value; // 使用后端返回的总数

  if (assessmentList.value.length > 0) {
    const uniqueUserIds = new Set();
    assessmentList.value.forEach(item => uniqueUserIds.add(item.userId));
    statsData.userCount = uniqueUserIds.size;

    let totalScore = 0;
    assessmentList.value.forEach(item => {
      totalScore += (item.inspectionScore || 0);
    });
    statsData.avgScore = Math.round(totalScore / assessmentList.value.length) || 0;

    const passCount = assessmentList.value.filter(
      item => item.conclusion === 1 || item.conclusion === 2 // 1:通过, 2:有条件通过
    ).length;
    statsData.passRate = Math.round((passCount / assessmentList.value.length) * 100) || 0;
  } else {
    statsData.userCount = 0;
    statsData.avgScore = 0;
    statsData.passRate = 0;
  }
};

const searchAssessments = () => {
  currentPage.value = 1;
  fetchAssessments();
};

const resetSearch = () => {
  searchForm.name = '';
  searchForm.status = null;
  currentPage.value = 1;
  fetchAssessments();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchAssessments();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchAssessments();
};

const handleInputClear = (key) => {
  if (key === 'name') searchForm.name = '';
  fetchAssessments();
};

const handleTypeChange = () => {
  currentPage.value = 1;
  fetchAssessments();
};

const getStatusText = (status) => STATUS_MAP[status] || status;
const getConclusionText = (conclusion) => CONCLUSION_MAP[conclusion] || conclusion;

const getScoreTagType = (score) => {
  if (score === null || score === undefined) return 'info';
  if (score >= 90) return 'success';
  if (score >= 75) return ''; // default
  if (score >= 60) return 'warning';
  return 'danger';
};

const getConclusionTagType = (conclusion) => {
  const types = {
    1: 'success', // 通过
    2: 'warning', // 有条件通过
    3: 'danger',  // 不通过
    4: 'info'     // 暂缓通过
  };
  return types[conclusion] || '';
};

const handleView = async (row) => {
  try {
    const response = await getAssessmentById(row.id);
    // 假设后端返回 { code: 200, data: InspectionLog }
    if (response.data.code === 200 && response.data.data) {
      currentAssessment.value = {
        ...response.data.data,
        // 如果后端 InspectionLog 中不直接包含 userName，需要从 userList 中查找
        userName: userList.value.find(u => u.id === response.data.data.userId)?.name || response.data.data.userName || '未知用户'
      };
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || '获取考察详情失败');
    }
  } catch (error) {
    console.error('获取考察详情失败:', error);
    ElMessage.error('获取考察详情失败，请稍后重试');
  }
};

const handleAdd = () => {
  isEdit.value = false;
  Object.assign(assessmentForm, initialAssessmentForm());
  if (assessmentFormRef.value) {
    assessmentFormRef.value.clearValidate();
  }
  editDialogVisible.value = true;
};

const handleEdit = (row) => {
  isEdit.value = true;
  if (assessmentFormRef.value) {
    assessmentFormRef.value.clearValidate();
  }
  // 从列表行数据填充表单，这些数据应该已经适配了后端 InspectionLog 格式
  const selectedUser = userList.value.find(u => u.id === row.userId);

  Object.assign(assessmentForm, {
    id: row.id,
    userId: row.userId,
    userName: selectedUser ? (selectedUser.name || selectedUser.nickname || selectedUser.username) : (row.userName || '未知用户'),
    status: row.status,
    recordDate: row.recordDate ? formatDate(row.recordDate, true) : '', // 确保是 YYYY-MM-DD HH:mm:ss
    checker: row.checker,
    inspectionScore: row.inspectionScore,
    conclusion: row.conclusion,
    inspectionContent: row.inspectionContent,
    advice: row.advice
  });
  editDialogVisible.value = true;
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除对 "${row.userName || '该用户'}" 的考察记录吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteAssessment(row.id);
      if (response.data.code === 200) {
        ElMessage.success(`删除考察记录成功`);
        fetchAssessments();
      } else {
        ElMessage.error(response.data.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除考察记录失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }).catch(() => {});
};

const submitAssessment = async () => {
  if (!assessmentFormRef.value) return;

  assessmentFormRef.value.validate(async (valid) => {
    if (!valid) return;

    submitting.value = true;
    try {
      const selectedUser = userList.value.find(user => user.id === assessmentForm.userId);
      const submitData = {
        id: assessmentForm.id,
        userId: assessmentForm.userId,
        status: assessmentForm.status,
        recordDate: assessmentForm.recordDate ? `${assessmentForm.recordDate}` : null, // 已经是 YYYY-MM-DD HH:mm:ss
        checker: assessmentForm.checker,
        inspectionScore: assessmentForm.inspectionScore,
        conclusion: assessmentForm.conclusion,
        inspectionContent: assessmentForm.inspectionContent,
        advice: assessmentForm.advice
      };

      console.log(submitData);

      const api = isEdit.value ? updateAssessment : addAssessment;
      const response = await api(submitData);

      if (response.data.code === 200) {
        ElMessage.success(isEdit.value ? '更新考察记录成功' : '添加考察记录成功');
        editDialogVisible.value = false;
        fetchAssessments();
      } else {
        ElMessage.error(response.data.msg || (isEdit.value ? '更新失败' : '添加失败'));
      }
    } catch (error) {
      console.error('提交考察记录失败:', error);
      ElMessage.error('提交失败，请稍后重试');
    } finally {
      submitting.value = false;
    }
  });
};

const debounceSearch = (() => {
  let timer;
  return () => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      currentPage.value = 1;
      fetchAssessments();
    }, 500);
  };
})();

const handleUserChange = (userId) => {
  if (!userId) {
    assessmentForm.userName = ''; // 虽然 userName 不提交，但表单中可能需要显示
    assessmentForm.userId = null;
    return;
  }
  const selectedUser = userList.value.find(user => user.id === userId);
  if (selectedUser) {
    assessmentForm.userName = selectedUser.name || selectedUser.nickname || selectedUser.username;
  }
};
</script>

<style scoped>
.assessment-list-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-card-content {
  display: flex;
  align-items: center;
  height: 100px;
  padding: 0 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 28px;
  color: white;
}

.bg-blue {
  background-color: #409EFF;
}

.bg-green {
  background-color: #67C23A;
}

.bg-orange {
  background-color: #E6A23C;
}

.bg-purple {
  background-color: #909399;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.assessment-content, .assessment-suggestions {
  white-space: pre-line;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.action-buttons .el-button {
  margin-left: 0 !important;
  width: 100%;
}

@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }
}
</style> 